import {defineStore} from "pinia"
import {login} from "../src/api/login";
import {getuserdata} from "../src/api/getdata";

export const mainStore = defineStore('main',{
    state:()=>{
        return {
            user:{
                username: localStorage.getItem('username') || '',
                userid: localStorage.getItem('userid') || null,
                userheader: localStorage.getItem('userheader') || null,
                userdesc: localStorage.getItem('userdesc') || null,
            },
            token: localStorage.getItem('token') || '',
            islogin: !!localStorage.getItem('token'),
        }
    },
    getters:{},
    actions:{
        loginin(userInfo){
            return new Promise((resolve, reject) => {
                login(userInfo)
                    .then((res) => {
                        console.log(res)
                        this.setToken(res.data)
                        this.token = res.data.token
                        localStorage.setItem('token', res.data.token)
                        resolve()
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        setToken(data) {
            this.user.username = data.username
            this.user.userid = data.userid
            this.user.userheader = data.header
            this.user.userdesc = data.userdesc
            this.islogin = true
            localStorage.setItem('username', data.username)
            localStorage.setItem('userid', data.userid)
            localStorage.setItem('userheader', data.header)
            localStorage.setItem('userdesc', data.userdesc)
        },
        loginout() {
            this.token = ''
            this.user.username = ''
            this.user.userid = ''
            this.islogin = false
            localStorage.setItem('username', '')
            localStorage.setItem('userid', '')
            localStorage.setItem('token', '')
            localStorage.clear()
        },
        updatainfo(userInfo){
            return new Promise((resolve, reject) => {
                getuserdata(userInfo)
                    .then((res) => {
                        console.log(res)
                        this.setToken(res.data)
                        resolve()
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        }
    }
})
